package entityVerify

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisService"
	"gitee.com/fierce_wolf/go-fox-edge-common/commSql"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Differ"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEntity"
)

func Initialize() {
	// 以mysql的DeviceObjectEntity表为基准，对DeviceValueEntity进行验证
	verifyDeviceValueEntity()

	// redis中的DeviceObjInfEntity是否为旧的无效版本
	verifyDeviceObjInfEntity()
}
func verifyDeviceValueEntity() {
	// 从数据库读取数据
	objectEntityList, err := commSql.QueryEntityList(edgeEntity.Type.DeviceObjectEntity.Type())
	if err != nil {
		return
	}

	// 从redis中读取数据
	valueEntityList, err := commRedisService.GetEntityMap(edgeEntity.Type.DeviceValueEntity.Type())
	if err != nil {
		return
	}

	// 重组mysql的数据
	mysqlMap := make(map[string]interface{})
	for _, entity := range objectEntityList {
		objectEntity := entity.(*edgeEntity.DeviceObjectEntity)

		valueEntity := edgeEntity.Type.DeviceValueEntity.Instance()
		valueEntity.DeviceName = objectEntity.DeviceName

		objectNames := Map.ComputeIfAbsent(mysqlMap, valueEntity.MakeServiceKey(), make(map[string]interface{}))
		list := objectNames
		list[objectEntity.ObjectName] = nil
	}

	// 重组redis的数据
	redisMap := make(map[string]interface{})
	for _, entity := range valueEntityList {
		valueEntity := entity.(*edgeEntity.DeviceValueEntity)

		objectNames := Map.ComputeIfAbsent(redisMap, valueEntity.MakeServiceKey(), make(map[string]interface{}))
		list := objectNames
		for key := range valueEntity.Params {
			list[key] = nil
		}

	}

	addList := make(map[string]interface{})
	delList := make(map[string]interface{})
	eqlList := make(map[string]interface{})
	Differ.Map.KStringVStruct(redisMap, mysqlMap, addList, delList, eqlList)

	// 在redis上，删除跟mysql没有的DeviceValueEntity
	for serviceKey := range delList {
		commRedisService.DeleteEntity(edgeEntity.Type.DeviceValueEntity.Type(), serviceKey)
	}

	// 删除对象不一致的redis数据
	for serviceKey := range eqlList {
		redis := redisMap[serviceKey].(map[string]interface{})
		mysql := mysqlMap[serviceKey].(map[string]interface{})

		// 比较对象级别是否存在差异
		diff, err := Differ.Set.DifferByKey(redis, mysql)
		if !diff || err != nil {
			continue
		}

		// 在redis上，删除跟mysql不一致的DeviceValueEntity
		commRedisService.DeleteEntity(edgeEntity.Type.DeviceValueEntity.Type(), serviceKey)
	}

}

func verifyDeviceObjInfEntity() {
	// 从redis中读取数据
	redisEntityList, err := commRedisService.GetEntityMap(edgeEntity.Type.DeviceObjInfEntity.Type())
	if err != nil {
		return
	}

	delList := make(map[string]interface{})
	for _, entity := range redisEntityList {
		deviceObjInfEntity := entity.(*edgeEntity.DeviceObjInfEntity)
		if deviceObjInfEntity.ValueType == "" {
			delList[deviceObjInfEntity.MakeServiceKey()] = nil
		}
	}

	// 在redis上，删除跟mysql没有的DeviceValueEntity
	for serviceKey := range delList {
		commRedisService.DeleteEntity(edgeEntity.Type.DeviceObjInfEntity.Type(), serviceKey)
	}
}
